/*
 *  Cero Project - Copyright   2006 The Cero Developement Team 
 *  (Michael Laguerre, Camille Roux, Matthieu Segret, Mathieu Sivade) 
 * 
 *  This program is free software; you can redistribute it and/or modify it 
 *  under the terms of the GNU General Public License as published by the Free 
 *  Software Foundation; either version 2 of the License, or (at your option) 
 *  any later version.
 * 
 *  This program is distributed in the hope that it will be useful, but 
 *  WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 
 *  or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 
 *  for more details.
 */

package org.ceroproject.plugin;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

import org.ceroproject.games.Game;
import org.ceroproject.ui.UserInterface;


class InterfacePlugin extends AbstractPlugin implements Plugin {

	private Class interfaceClass;

	private UserInterface dumbInstance;

	private Map<Class<? extends Game>, Collection<InterfaceModulePlugin>> modules = new HashMap<Class<? extends Game>, Collection<InterfaceModulePlugin>>();

	public InterfacePlugin(Class<? extends UserInterface> uiClass) throws NotInstantiableException {
		interfaceClass = uiClass;
		dumbInstance = (UserInterface) tryInstanciante(interfaceClass);
	}

	public String getPluginName() {
		return dumbInstance.getUserInterfaceName();
	}

	public UserInterface newInterfaceInstance() {
		try {
			return (UserInterface) interfaceClass.newInstance();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	void addModulePlugin(InterfaceModulePlugin imp) {
		Collection<InterfaceModulePlugin> gamemods = modules.get(imp
				.getGameType());
		if (gamemods == null)
			gamemods = new HashSet<InterfaceModulePlugin>();
		gamemods.add(imp);
		modules.put(imp.getGameType(), gamemods);
	}

	Collection<InterfaceModulePlugin> getModulesForGame(
			Class<? extends Game> gameclass) {
		Collection<InterfaceModulePlugin> result = new ArrayList<InterfaceModulePlugin>();

		if (gameclass == null)
			result.addAll(modules.get(null));
		else {
			for (Map.Entry<Class<? extends Game>, Collection<InterfaceModulePlugin>> it : modules
					.entrySet()) {
				if (it.getKey() == null
						|| gameclass.isAssignableFrom(it.getKey())) {
					result.addAll(it.getValue());
				}
			}
		}

		return result;
	}
}
